package beautiful.butterfly.server.httpserver.handler;

import beautiful.butterfly.server.httpserver.mvc.SessionManager;
import beautiful.butterfly.server.httpserver.mvc.core.ActionContext;
import beautiful.butterfly.server.httpserver.mvc.http.*;

import java.util.UUID;


public class SessionHandler {


    private final SessionManager sessionManager;

    private final String sessionKey;
    private final int timeout;

    SessionHandler(SessionManager sessionManager) {

        this.sessionManager = sessionManager;

        this.sessionKey = HttpConst.DEFAULT_SESSION_KEY;
        this.timeout = 18000;
    }

    public Session createSession(Request request) {
        Session session = getSession(request);
        Response response = ActionContext.getResponse();
        if (null == session) {
            return createSession(request, response);
        } else {
            if (session.expired() < System.currentTimeMillis() / 1000) {
                removeSession(session);
            }
        }
        return session;
    }

    private Session createSession(Request Request, Response Response) {

        long now = System.currentTimeMillis() / 1000;
        long expired = now + timeout;

        String sessionId = UUID.randomUUID().toString().replace("-", "");
        Cookies Cookies = new Cookies();
        Cookies.name(sessionKey);
        Cookies.value(sessionId);
        Cookies.httpOnly(true);
        Cookies.secure(false);

        Session session = new HttpSession();
        session.id(sessionId);
        session.created(now);
        session.expired(expired);
        sessionManager.addSession(session);

        Request.cookie(Cookies);
        Response.cookie(Cookies);


        return session;
    }

    private void removeSession(Session session) {
        session.getAttributeMap().clear();
        sessionManager.remove(session);

    }

    private Session getSession(Request Request) {
        String cookieHeader = Request.cookie(sessionKey);
        if (!(cookieHeader != null)) {
            return null;
        }
        return sessionManager.getSession(cookieHeader);
    }

}
